<?php

class AutoRun extends CConsoleCommand {
	public function run($args) {
		$curdate = date("Y-m-d");
		//$list= Yii::app()->db->createCommand('select * from member_position where substr(expire_date,1,10)>=:expire_date')->bindValue('expire_date',$expdate)->queryAll();
		$list = Yii::app()->db->createCommand("select * from member_position where substr(expire_date,1,10) >='" . $curdate . "'")->queryAll();

		foreach ($list as $position) {
			$sql = "select * from member_transaction_history where
					   substr(transaction_date,1,10) = '" . $curdate . "' and member_id=" . $position['member_id'] .
                    " and positions=" . $position["no_of_positions"];
			$tHistory = Yii::app()->db->createCommand($sql)->queryAll();
			/* if not empty means already process run for this postions */
			if (!empty($tHistory)) {
				// Log message add here.
				//echo "Transaction on current date for that positons:" . $position["member_positions_id"] . " already exists";
				Yii::log("Transaction on current date for that positons:" . $position["member_positions_id"] . " already exists",'error','application');
				continue;
			}

			$sql = "select * from member_transaction_history where member_transaction_history_id = (
                    select max( member_transaction_history_id ) from member_transaction_history 
                    where member_id =" . $position['member_id'] . ")";

			$_lh = Yii::app()->db->createCommand($sql)->queryAll();
			$balance = 0;
			if (!empty($_lh)) {
				$_history = $_lh[0];
				if (!empty($_history)) {
					$balance = $_history['balance'];
				}
			}
			$mthModel = new MemberTransactionHistory();
			$mthModel->member_id = $position["member_id"];
			$mthModel->credit = $position["no_of_positions"] * 10 * 2 / 100;
			$mthModel->transaction_date = date("Y-m-d H:i:s");
			$mthModel->balance = $balance + $mthModel->credit;
			$mthModel->particulars = "Added profit amount for positions id :" . $position["member_positions_id"] . " and number of positions :" . $position["no_of_positions"];
			$mthModel->positions = $position["no_of_positions"];
			$mthModel->save();
			Yii::log("Member transaction history added for "+$position["member_id"],'info','application');
			//echo "Member transaction history added...";
		}
	}
}
?>